package misc

import (
	"dhfshop/controllers/base"
	//"time"
	//"strings"
	"dhfshop/models/misc"
	"dhfshop/models/org"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type ApiInfoController struct {
	base.BaseController
}

func (this *ApiInfoController) Get() {
	curPartnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	user, err := org.GetUserByPartnerIdAndApi(curPartnerId, 1)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	misc.ApiInfoExist(curPartnerId, user.UserName)
	apiInfo, err := misc.GetApiInfo(curPartnerId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	this.Data["json"] = apiInfo
	this.ServeJSON()
}

func (this *ApiInfoController) Put() {
	v := misc.ApiInfo{}
	this.ParseForm(&v)
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	valid := validation.Validation{}
	valid.Required(v.PartnerId, "partner_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"partner_id", "api_id", "api_secret"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		if err := misc.UpdateApiInfoByPartnerId(&v, updateFields...); err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	apiInfo, err := misc.GetApiInfo(v.PartnerId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	this.Data["json"] = apiInfo
	this.ServeJSON()
}
